<template>
	<view>
		<uni-nav-bar dark title="创建机构" fixed :statusBar="true" left-icon="left" @clickLeft="onLeft">
		</uni-nav-bar>
		<view class="content">
			<uni-forms class="form" ref="baseForm" :modelValue="baseFormData" :rules="customRules">
				<uni-forms-item class="logo" labelWidth="280rpx" label="机构logo"  name="organizationLogo">
					<uni-file-picker  :value="selectcoachPhoto" :autoUpload="false" limit="1" :del-icon="false" disable-preview
						:imageStyles="imageStyles" file-mediatype="image" @progress="progress"
						@select="(data) => select(data, 1)">选择</uni-file-picker>
				</uni-forms-item>
				<uni-forms-item class="logo" labelWidth="280rpx" label="上传封面"  name="organizationPhoto">
					<uni-file-picker :value="selectcoachPhoto1" :autoUpload="false" limit="1" :del-icon="false" disable-preview
						:imageStyles="imageStyles" file-mediatype="image" @progress="progress"
						@select="(data) => select(data, 2)">选择</uni-file-picker>
				</uni-forms-item>
				<uni-forms-item labelWidth="280rpx" label="名称" required name="name">
					<uni-easyinput v-model="baseFormData.name" placeholder="请输名称" />
				</uni-forms-item>
				<uni-forms-item labelWidth="280rpx" label="地区"  name="area">
					
					<uni-data-picker style="opacity: 1;" ref="dataPrickerarea" :value="baseFormData.area" :localdata="localData" popup-title="请选择省市区"
						@change="onchange" @nodeclick="onnodeclick">
							<view style="padding-left: 10px;" v-if="baseFormData.area">{{baseFormData.area}}</view>
							<view v-else style="color: #999;padding-left: 10px;font-size: 12px;">请选择省市区</view>
					</uni-data-picker>
				</uni-forms-item>
				<uni-forms-item labelWidth="280rpx" label="详细地址"  name="address">
					<uni-easyinput v-model="baseFormData.address" placeholder="请输详细地址" />
				</uni-forms-item>
				<uni-forms-item labelWidth="280rpx" label="机构介绍"  name="address">
					<uni-easyinput v-model="baseFormData.remark" placeholder="请输机构介绍" />
				</uni-forms-item>
				<uni-forms-item labelWidth="280rpx" label="联系电话"  name="phoneNumber">
					<uni-easyinput v-model="baseFormData.phoneNumber" placeholder="请输联系电话" />
				</uni-forms-item>
				<uni-forms-item labelWidth="280rpx" label="邮箱"  name="email">
					<uni-easyinput v-model="baseFormData.email" placeholder="请输邮箱" />
				</uni-forms-item>
			</uni-forms>
		</view>
		<view class="btn">
			<button class="" @click="onUp">上一步</button>
			<button class="" @click="onNext" :loading="disabled" :disabled="disabled">{{this.id ? '修改' : '创建'}}</button>
		</view>
	</view>
</template>

<script>
	import {
		uploadAvatar,
	} from '@/api/basketballTeam/index.js'
	const cityRows = require('@/plugins/data.json')
	import	{postorganization,getdynamic,
	putorganization} from '@/api/mechanism/index.js'
	import	{imageUrl} from '@/config.js'
	export default {
		data() {
			return {
				disabled: false,
				type: '',
				selected: '',
				baseFormData: {
					organizationLogo: '',
					organizationPhoto: '',
					area: '',
					name: '',
					address: '',
					remark: '',
					phoneNumber: '',
					email: ''
				},
				selectcoachPhoto1: [],
				selectcoachPhoto: [],
				imageStyles: {
					width: '100rpx',
					height: '100rpx',
					border: {
						radius: '50%'
					}
				},
				customRules: {
					
					name: {
						rules: [{
							required: true,
							errorMessage: '请输入名称'
						}]
					}
					
				},
				id: ''
			}
		},
		methods: {
			onDataPrick() {
				this.$refs.dataPrickerarea.show()
			},
			onLeft() {
				uni.navigateBack();
			},
			onNext() {
				this.disabled = true;
				this.$refs.baseForm.validate().then(res =>{
					if (this.id) {
						putorganization({...this.baseFormData,type: this.type,id:this.id}).then(res => {
							this.$modal.msg(res.msg)
							this.disabled = false;
							setTimeout(() => {
								uni.redirectTo({
									url:'/pages/mechanism/list'
								})
							}, 600)
							
						}).catch(errr => {
							this.disabled = false;
						})
					} else {
						postorganization({...this.baseFormData,type: this.type}).then(res => {
							this.$modal.msg(res.msg)
							this.disabled = false;
							setTimeout(() => {
								uni.redirectTo({
									url:'/pages/mechanism/list' + (this.selected ? '?selected=1': '')
								})
							}, 600)
						}).catch(errr => {
							this.disabled = false;
						})
					}
					
				}).catch(err => {
					this.disabled = false;
				})
			},
			onUp() {
				uni.navigateBack()
			},
			select(e, index) {
				uploadAvatar({
					file: e.tempFiles[0].file
				}).then(res => {
					console.log(res, '---')
					if (index == 1) {
						this.baseFormData.organizationLogo = res.data;
					} else {
						this.baseFormData.organizationPhoto = res.data;
					}
				})
			},
			// 节点变化后 （并非已经选择完毕）
			onnodeclick(node) {
				// console.log(JSON.stringify(node))
			},

			// 整体选择完成以后
			onchange(e) {
				const value = e.detail.value
				console.log(value)
				let str = ''
				value.forEach(item => {
					str += item.text
				})
				this.baseFormData.area = str
			},



			// 省市区数据树生成
			get_city_tree() {
				let res = []
				if (cityRows.length) {
					// 递归生成
					res = this.handleTree(cityRows)
				}
				return res
			},


			/**
			 * 递归生成树结构数据 - 省市区
			 * 
			 * @param {Object} data
			 * @param {String} parent_code 上级ID | null代表需要顶部菜单
			 * @author Rudon  https://rudon.blog.csdn.net/
			 * 
			 * 源数据：
			 * {
			 * 	  "code": "110100", 
			 *    "name": "北京市",
			 *    "pinyin": "beijingshi",
			 *    "zip_code": "100000",
			 *    "parent_code": "110000",
			 *    "type": 1,
			 *    "first_letter": "B"
			 * }
			 * 
			 * 目标：
			 * {
			 *   text: "XX市",
			 *   value: "810000",
			 *   children: []
			 * }
			 * 
			 */
			handleTree(data, parent_code = null) {
				let res = []

				let keys = {
					id: 'code',
					pid: 'parent_code',
					children: 'children',

					text: 'name',
					value: 'code'
				}

				let oneItemDEMO = {
					text: '',
					value: '',
					children: []
				}
				let oneItem = {}

				// 循环
				for (let index in data) {
					// 判断
					if (parent_code === null) {
						// 顶级菜单 - 省
						if (!data[index].hasOwnProperty(keys.pid) || data[index][keys.pid] == parent_code) {
							// 不存在parent_code，或者已匹配
							oneItem = JSON.parse(JSON.stringify(oneItemDEMO))
							oneItem.text = data[index][keys.text]
							oneItem.value = data[index][keys.value]

							// 递归下去
							oneItem.children = this.handleTree(data, data[index][keys.id])
							res.push(oneItem)

						} else {
							// 匹配不到，跳过
						}

					} else {
						// 非顶级菜单 - 市、区、街道
						if (data[index].hasOwnProperty(keys.pid) && data[index][keys.pid] == parent_code) {
							// 已匹配
							oneItem = JSON.parse(JSON.stringify(oneItemDEMO))
							oneItem.text = data[index][keys.text]
							oneItem.value = data[index][keys.value]

							// 递归下去
							oneItem.children = this.handleTree(data, data[index][keys.id])
							res.push(oneItem)

						} else {
							// 匹配不到，跳过
						}

					}

				}

				return res
			},
		},
		onLoad({type,id, selected}) {
			this.type  = type
			this.localData = this.get_city_tree()
			this.id = id;
			this.selected = selected;
			if (id) {
				getdynamic(id).then(res =>  {
					this.baseFormData = res.data;
					let {area} = res.data;
					this.baseFormData.area = area
					this.selectcoachPhoto = [{url: imageUrl + res.data.organizationLogo}]
					this.selectcoachPhoto1 = [{url: imageUrl + res.data.organizationPhoto}]
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.content {
		padding: 30rpx 20rpx;

		.logo {
			display: flex;
			align-items: center;
			padding-bottom: 40rpx;
		}
	}
	.btn{
		display: flex;
		width: 90%;
		left: 0;
		right: 0;
		margin: auto;
		// position: fixed;
		bottom: 20%;
		button {
			width: 48%;
			background-color: $btn-bg-color;
			color: #fff;
			&:nth-child(1) {
				background-color: #fff;
				border: 1px  solid $btn-bg-color;
				color: $btn-bg-color;
			}
		}
	}
</style>